﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System.Collections.ObjectModel;
using System.Windows;
using CastingWellEquipmentGUI.ViewModel.Modal;
using CastingWellEquipmentGUI.ViewModel.Modal.AlarmHistoryQuery;
using CastingWellEquipmentGUI.ViewModel.Modal.AlarmsHistory;
using Confluent.Kafka;
using CastingWellEquipmentGUI.Utils;
using Newtonsoft.Json;

namespace CastingWellEquipmentGUI.ViewModel.Pages
{
    public class AlarmHistoryQueryPageViewModel : ViewModelBase
    {
        public string DeleteSource;

        #region 下拉框使用
        private ComplexInfoModel combboxItem;
        /// <summary>
        /// 下拉框选中信息
        /// </summary>
        public ComplexInfoModel CombboxItem
        {
            get { return combboxItem; }
            set { combboxItem = value; RaisePropertyChanged(() => CombboxItem); }
        }

        private ObservableCollection<ComplexInfoModel> combboxList;
        /// <summary>
        /// 下拉框列表
        /// </summary>
        public ObservableCollection<ComplexInfoModel> CombboxList
        {
            get { return combboxList; }
            set { combboxList = value; RaisePropertyChanged(() => CombboxList); }
        }
        #endregion
        #region 分页使用
        /// <summary>
        /// 每页数量
        /// </summary>
        private int itemCount = 15;

        /// <summary>
        /// 总数量
        /// </summary>
        private int totalDataCount = 0;

        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPageNumber
        {
            get
            {
                int totalPageNumber = totalDataCount / itemCount;
                if (totalDataCount % itemCount > 0)
                {
                    totalPageNumber++;
                }
                return totalPageNumber;

            }
        }
        /// <summary>
        /// 总数据量
        /// </summary>
        public int TotalDataCount
        {
            get { return totalDataCount; }
            set
            {
                totalDataCount = value;
                RaisePropertyChanged("TotalDataCount");
                RaisePropertyChanged("TotalPageNumber");
            }
        }

        /// <summary>
        /// 当前所在页数
        /// </summary>
        private int _CurrentPageNumber = 1;
        /// <summary>
        /// 当前所在页数
        /// </summary>
        public int CurrentPageNumber
        {
            get { return _CurrentPageNumber; }
            set
            {
                _CurrentPageNumber = value;
                RaisePropertyChanged("CurrentPageNumber");
            }
        }
        /// <summary>
        /// 上一页页数
        /// </summary>
        public int PreviousPageNumber
        {
            get
            {
                if (_CurrentPageNumber - 1 > 0)
                {
                    return _CurrentPageNumber - 1;
                }
                return 1;
            }

        }
        /// <summary>
        /// 下一页页数
        /// </summary>
        public int NextPageNumber
        {
            get
            {
                if (_CurrentPageNumber + 1 <= TotalPageNumber)
                {
                    return _CurrentPageNumber + 1;
                }
                return _CurrentPageNumber;
            }

        }

        /// <summary>
        /// 选中的项目
        /// </summary>
        private AlarmsHistoryModel _SelectedItemModel;
        /// <summary>
        /// 选中的项目
        /// </summary>
        public AlarmsHistoryModel SelectedItemModel
        {
            get { return _SelectedItemModel; }
            set
            {
                _SelectedItemModel = value;
                RaisePropertyChanged("SelectedItemModel");
            }
        }

        /// <summary>
        /// 分页页码集合
        /// </summary>
        private ObservableCollection<PageNumerModel> _PageNumers = new ObservableCollection<PageNumerModel>();
        /// <summary>
        /// 分页页码集合
        /// </summary>
        public ObservableCollection<PageNumerModel> PageNumers
        {
            get => _PageNumers;
            set
            {
                _PageNumers = value;
                RaisePropertyChanged("PageNumers");
            }
        }
        #endregion 分页使用
        /// <summary>
        /// 跳转到指定页面命令
        /// </summary>
        public DelegateCommand GoToPageByNumberCommand { get; set; }
        /// <summary>
        /// 跳转到指定页面并关闭AllPageNumberPanel窗体命令
        /// </summary>
        public DelegateCommand GoToPageByNumberAndCloseAllPageNumberPanelCommand { get; set; }

        /// <summary>
        /// 显示更改到指定页面命令
        /// </summary>
        public DelegateCommand ChangeCurrentPageNumberCommand { get; set; }
        /// <summary>
        /// 取消命令
        /// </summary>
        public DelegateCommand CancelCommand { get; set; }
        /// <summary>
        /// 主列表数据
        /// </summary>
        private ObservableCollection<AlarmsHistoryModel> _DataCollection;
        /// <summary>
        /// 主列表数据
        /// </summary>
        public ObservableCollection<AlarmsHistoryModel> DataCollection
        {
            get { return _DataCollection; }
            set
            {
                _DataCollection = value;
                RaisePropertyChanged("DataCollection");
            }
        }
        /// <summary>
        /// 搜索条件
        /// </summary>
        private RecipeTableByVerification _Search = new RecipeTableByVerification();
        /// <summary>
        /// 搜索条件
        /// </summary>
        public RecipeTableByVerification Search
        {
            get { return _Search; }
            set
            {
                _Search = value;
                RaisePropertyChanged("Search");
            }

        }
        private AlarmsHistoryModel _AlarmsHistoryModel = new AlarmsHistoryModel();
        /// <summary>
        /// 搜索条件
        /// </summary>
        public AlarmsHistoryModel AlarmsHistoryModel
        {
            get { return _AlarmsHistoryModel; }
            set
            {
                _AlarmsHistoryModel = value;
                RaisePropertyChanged("AlarmsHistoryModel");
            }

        }
        /// <summary>
        /// 当前查看的配方实体类
        /// </summary>
        private AlarmsHistoryModel _CurrentModel = new AlarmsHistoryModel();
        /// <summary>
        /// 当前查看的配方实体类
        /// </summary>
        public AlarmsHistoryModel CurrentModel
        {
            get { return _CurrentModel; }
            set
            {
                _CurrentModel = value;
                RaisePropertyChanged("CurrentModel");
            }

        }
        /// <summary>
        /// 搜索命令
        /// </summary>
        public DelegateCommand SearchCommand { get; set; }
        /// <summary>
        /// 显示日历窗体命令
        /// </summary>
        public DelegateCommand ShowCalendarCommand { get; set; }
        /// <summary>
        /// 类别搜索条件
        /// </summary>
        private List<string> _TypeConditions = new List<string>();
        /// <summary>
        /// 类别搜索条件
        /// </summary>
        public List<string> TypeConditions
        {
            get { return _TypeConditions; }
            set
            {
                _TypeConditions = value;
                RaisePropertyChanged("TypeConditions");
            }
        }
        /// <summary>
        /// Kafka报警归档指令topic
        /// </summary>
        private TopicPartition topicAlarmCmdPartition = new TopicPartition("BusinessCmd", new Partition(0));
        /// <summary>
        /// Kafka消费对象
        /// </summary>
        private static IConsumer<string, object> consumer = null;

        public AlarmHistoryQueryPageViewModel()
        {
            // 实例化Kafka生产与消费对象
            InitKafkaInfo();

            CombboxList = new ObservableCollection<ComplexInfoModel>() {
                          new ComplexInfoModel(){ Key="0",Text="全部" },
                          new ComplexInfoModel(){ Key="1",Text="一级报警" },
                          new ComplexInfoModel(){ Key="2",Text="二级报警" },
                          new ComplexInfoModel(){ Key="3",Text="三级报警" }};

            combboxItem = CombboxList[0];  // 默认选中第一个
            InitDataCollection();
            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };


            ShowCalendarCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ShowCalendarHandler)
            };


            CancelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(CancelHandler)
            };
            GoToPageByNumberCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(GoToPageByNumberHandler)
            };
            GoToPageByNumberAndCloseAllPageNumberPanelCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(GoToPageByNumberAndCloseAllPageNumberPanelHandler)
            };
            ChangeCurrentPageNumberCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ChangeCurrentPageNumberHandler)
            };
            //重新加载数据
            Messenger.Default.Register<string>(this, "ReLoadRecipeManagementPageData", (message) =>
            {
                Search = new RecipeTableByVerification();
                Search.MSC_DateCreated_Start = "点击设置开始时间";
                Search.MSC_DateCreated_End = "点击设置结束时间";
                InitDataCollection();
            });
            //获取传递过来的时间参数开始
            Messenger.Default.Register<string>(this, "SetStartDate", (message) =>
            {
                Search.MSC_DateCreated_Start = message;
            });

            //获取传递过来的时间参数结束
            Messenger.Default.Register<string>(this, "SetEndDate", (message) =>
            {
                Search.MSC_DateCreated_End = message;
            });

            Search.MSC_DateCreated_Start = "点击设置开始时间";
            Search.MSC_DateCreated_End = "点击设置结束时间";

            
        }

        /// <summary>
        /// 实例化Kafka生产与消费对象
        /// </summary>
        private void InitKafkaInfo()
        {
            ConsumerConfig config = new ConsumerConfig();
            config.BootstrapServers = SystemConfig.dataBaseIpAddress + ":9092"; ;
            config.GroupId = "group.1";
            config.AutoOffsetReset = AutoOffsetReset.Earliest;
            config.EnableAutoCommit = false;

            var builder = new ConsumerBuilder<string, object>(config);
            builder.SetValueDeserializer(new KafkaConverter());//设置反序列化方式
            consumer = builder.Build();
            consumer.Assign(new TopicPartition("BusinessCmdResult", new Partition(0)));//从指定的Partition订阅消息使用Assign方法
        }

        /// <summary>
        /// 发送报警记录归档指令给网关服务器
        /// </summary>
        /// <returns>true=成功，false=失败</returns>
        private bool sendAlarmArchivCmdToServer()
        {
            BusinessCmd businessCmd = new BusinessCmd
            {
                BusinessCmdCode = 1,
                Guid = Guid.NewGuid().ToString()
            };
            return KafkaHelper.SendGatewayBusinessCmd(businessCmd);
        }

        /// <summary>
        /// 跳转到更改页码的列表
        /// </summary>
        /// <param name="obj"></param>
        private void GoToPageByNumberAndCloseAllPageNumberPanelHandler(object obj)
        {
            GoToPageByNumberHandler(obj);
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideAllPageNumberPanelForRecipeManage"));
        }
        /// <summary>
        /// 打开更改页码窗体
        /// </summary>
        /// <param name="obj"></param>
        private void ChangeCurrentPageNumberHandler(object obj)
        {
            PageNumers = new ObservableCollection<PageNumerModel>();
            for (int i = 0; i < TotalPageNumber; i++)
            {
                PageNumers.Add(new PageNumerModel() { PageNumberStr = (i + 1).ToString() });
            }
            if (PageNumers.Count > 1)
            {
                WindowManager.ShowDialog("AllPageNumberPanelForRecipeManageWindow", "");
            }
        }
        /// <summary>
        /// 跳转到指定页面命令的处理器
        /// </summary>
        /// <param name="obj"></param>
        private void GoToPageByNumberHandler(object obj)
        {
            switch (obj.ToString())
            {
                case "PreviousPage":
                    CurrentPageNumber = PreviousPageNumber;
                    break;
                case "NextPage":
                    CurrentPageNumber = NextPageNumber;
                    break;
                case "FirstPage":
                    CurrentPageNumber = 1;
                    break;
                case "LastPage":
                    CurrentPageNumber = TotalPageNumber;
                    break;
                default:
                    CurrentPageNumber = int.Parse(obj.ToString());
                    break;
            }
            InitDataCollection();
        }
        /// <summary>
        /// 取消命令处理方法
        /// </summary>
        /// <param name="obj"></param>
        private void CancelHandler(object obj)
        {
            //重新加载数据
            Messenger.Default.Send<string>("", "ReLoadRecipeManagementPageData");
            //跳转到配方管理页
            Messenger.Default.Send<string>("RecipeManagementPage", "GoToPage");
        }

        /// <summary>
        /// 显示日历窗体命令处理方法
        /// </summary>
        /// <param name="obj"></param>
        private void ShowCalendarHandler(object obj)
        {
            WindowManager.ShowModalCalendar("CalendarWindow", obj.ToString());
        }
        /// <summary>
        /// 搜索命令处理器方法
        /// </summary>
        /// <param name="obj"></param>
        private void SearchHandler(object obj)
        {
            InitDataCollection();
        }

        /// <summary>
        /// 初始化主列表数据
        /// </summary>
        private void InitDataCollection()
        {
            // 先将报警记录缓存数据归档到SQL数据库中
            if (!sendAlarmArchivCmdToServer())
            {
                // 归档失败
                MessageBoxResult result = MessageBox.Show("查询失败！", "信息提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            string baseSearchSql = @"SELECT ROW_NUMBER() OVER (
                                                                ORDER BY a.EventTime DESC
                                                               ) as rownumber,
                                     a.EventTime,a.AlarmText,a.Active,a.ConditionID,a.Source,a.Severity,a.SubAlarmType                  
                                    ,b.EventTime as RelieveTime FROM (SELECT * FROM Log_Alarm where Active = 1) a 
                                    LEFT JOIN (SELECT * FROM Log_Alarm where Active = 0) b ON a.EventAssociationID = b.EventAssociationID  WHERE 1 = 1 ";
            if (AlarmsHistoryModel.AlarmText != null && AlarmsHistoryModel.AlarmText.Trim().Length > 0)
            {
                baseSearchSql += " AND a.AlarmText LIKE '%" + AlarmsHistoryModel.AlarmText + "%'";
            }

            if (CombboxItem.Key + "" != "0" && (CombboxItem.Key + "").Trim().Length > 0)
            {
                baseSearchSql += " AND a.Severity = " + CombboxItem.Key;
            }
            if (Search.MSC_DateCreated_Start != null && Search.MSC_DateCreated_Start.Trim().Length > 0 && Search.MSC_DateCreated_Start != "点击设置开始时间")
            {
                baseSearchSql += " AND a.EventTime  >= '" + Search.MSC_DateCreated_Start + "'";
            }
            if (Search.MSC_DateCreated_End != null && Search.MSC_DateCreated_End.Trim().Length > 0 && Search.MSC_DateCreated_End != "点击设置结束时间")
            {
                baseSearchSql += " AND b.EventTime  < '" + Search.MSC_DateCreated_End + "'";
            }
            for (int i = 0; i < TypeConditions.Count; i++)
            {
                if (i == 0)
                {
                    baseSearchSql += " AND ( MSC_Type = '" + TypeConditions[i] + "'";
                }
                else
                {
                    baseSearchSql += " OR MSC_Type = '" + TypeConditions[i] + "'";
                }
                if (i == TypeConditions.Count - 1)
                {
                    baseSearchSql += " ) ";
                }
            }
            string pageingSql = @"SELECT TOP " + itemCount + @" * 
                                  FROM (" + baseSearchSql + @") temp_row
                                  WHERE rownumber > ((" + CurrentPageNumber + @" - 1 ) * " + itemCount + @" ); ";

            DataCollection = DapperToolsGatewayServer.QueryOc<AlarmsHistoryModel>(pageingSql);
            //总数据量
            TotalDataCount = DapperToolsGatewayServer.GetCount(baseSearchSql);
            for (int i = 0; i < DataCollection.Count; i++)
            {
                DataCollection[i].OrderNo = (i + 1);
            }
        }


    }
}
